# -*- coding: utf-8 -*-
# @Time : 2021/2/8 15:55
# @Author : zhangcheng
# @Software: PyCharm

from service.base_service import BaseHandler
from datetime import datetime
from controller.comment_controller import CommentController


class CommentSearchHandler(BaseHandler):
    # 查询使用GET请求，可以通过id、writer或reader查找留言
    def get(self):
        autoid = self.get_query_argument("autoid", None)
        writer = self.get_query_argument("writer", None)
        reader = self.get_query_argument("reader", None)
        if not autoid and not writer and not reader:
            self.write({"message": "请输入查询的id、writer或reader字段", "error": "查询字段为空"})
            return
        kwargs = {"autoid": autoid, "writer": writer, "reader": reader}
        result = CommentController.get(**kwargs)
        self.write(result)


class CommentCreateHandler(BaseHandler):
    # 创建使用post请求，必须传入id,from和reader，可以没有content，默认为""
    def post(self):
        autoid = self.get_body_argument("autoid", None)
        writer = self.get_body_argument("writer", None)
        reader = self.get_body_argument("reader", None)
        if not autoid or not writer or not reader:
            self.write({"message": "autoid, writer和reader是必须字段，请重新提交", "erorr": "创建字段为空"})
            return
        content = self.get_body_argument("content", "")
        time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        kwargs = {"autoid": autoid, "writer": writer, "reader": reader, "content": content, "time": time}
        result = CommentController.add(**kwargs)
        self.write(result)


class CommentUpdateHandler(BaseHandler):
    # 更新使用post请求，要求传入更新记录的autoid和content
    def post(self):
        # 通过输入的autoid来找到某条数据进行更新，只能更新content
        autoid = self.get_body_argument("autoid", None)
        newcontent = self.get_body_argument("content", None)
        if not autoid:
            self.write({"message": "autoid是必须字段，请重新提交", "error": "更新字段为空"})
            return
        time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        kwargs = {"autoid": autoid, "content": newcontent, "time": time}
        result = CommentController.update(**kwargs)
        self.write(result)


class CommentDeleteHandler(BaseHandler):
    # 删除使用get请求，要求传入autoid或writer或reader
    def get(self):
        # 通过输入的id来删除一条或根据writer或reader来删除一组
        autoid = self.get_query_argument("autoid", None)
        writer = self.get_query_argument("writer", None)
        reader = self.get_query_argument("reader", None)
        if not autoid and not writer and not reader:
            self.write({"message": "请输入删除的autoid、writer或reader字段", "error": "删除字段为空"})
            return
        kwargs = {"autoid": autoid, "writer": writer, "reader": reader}
        result = CommentController.delete(**kwargs)
        self.write(result)